<!-- 文件管理 -->
<template>
  <div class="list-card-container">
    <a-card title="文件管理" class="general-card">
      <!-- 查询表单 -->
      <table-search
        ref="searchRef"
        :data-source="SEARCH_FORM"
        @change="searchFile"
      />

      <!-- 表格 -->
      <AddDrawer
        clickword="上传文件"
        title="上传文件"
        :data-source="UPLOAD_FORM"
        narrow
        show-file-upload
        :file-upload="{
          draggable: true,
          span: 24,
          noBusinessKey: true,
        }"
        style="margin-bottom: 10px"
        @change="afterUpload"
      >
        <template #icon>
          <icon-upload />
        </template>
      </AddDrawer>
      <AdvancedTable
        :columns="COLUMNS_FILE"
        :data="fileList"
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        :scroll="{ x: 1000 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!--插槽，操作-->
        <template #operation="{ record }">
          <a-space>
            <a-link @click="handleDownload(record)">下载</a-link>
            <a-popconfirm
              content="确定删除此文件吗？"
              type="warning"
              @ok="removeFile(record)"
            >
              <a-link> 删除 </a-link>
            </a-popconfirm>
          </a-space>
        </template>
      </AdvancedTable>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    FileRecord,
    FileParams,
    FileRecordSearchReq,
  } from '@/api/model/fileModel';
  import { queryFileRecordPage, deleteFile } from '@/api/file';
  import { Pagination } from '@/types/global';
  import { ref, onMounted, reactive } from 'vue';
  import TableSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AddDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  import AdvancedTable from '@/common/components/cac-components/advanced-table/index.vue';

  const searchRef = ref<any>();
  // 查询表单
  const SEARCH_FORM: any[] = [
    { fieldName: 'businessType', labelText: '业务类别', type: 'text' },
    { fieldName: 'path', labelText: '文件路径', type: 'text' },
    { fieldName: 'type', labelText: '文件类型', type: 'text' },
    { fieldName: 'createTime', labelText: '创建时间', type: 'datetimeRange' },
  ];

  const loading = ref<boolean>(false);

  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });

  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };

  // func: 查询文件列表
  const searchFile = async (reqdata: FileRecordSearchReq = {}) => {
    const params: FileParams = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...reqdata,
    };
    loading.value = true;
    try {
      const { data } = await queryFileRecordPage(params);
      pagination.total = Number(data.total);
      fileList.value = data.list;
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    searchFile();
  });

  // 表格
  const fileList = ref<FileRecord[]>([]);
  const COLUMNS_FILE: TableColumnData[] = [
    // {
    //   title: '序号',
    //   align: 'center',
    //   dataIndex: 'index',
    //   width: 80,
    //   render: ({ rowIndex }) => rowIndex + 1,
    //   fixed: 'left',
    // },
    {
      title: '业务类别',
      dataIndex: 'businessType',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '文件路径',
      dataIndex: 'path',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: 'url',
      dataIndex: 'url',
      width: 300,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '文件大小',
      dataIndex: 'size',
      align: 'right',
      render: ({ record }) => formatBytes(record.size),
      width: 90,
    },
    {
      title: '文件类型',
      dataIndex: 'type',
      ellipsis: true,
      tooltip: true,
      width: 120,
    },
    { title: '上传时间', dataIndex: 'createTime', width: 180 },
    {
      title: '操作',
      dataIndex: 'operation',
      slotName: 'operation',
      width: 120,
      align: 'center',
      fixed: 'right',
    },
  ];

  // 文件上传
  const UPLOAD_FORM: any[] = [
    // {
    //   labelText: '文件',
    //   fieldName: 'file',
    //   type: 'file',
    //   draggable: true,
    //   col: 24,
    // },
  ];

  const BYTES_ARRAY = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  // 将文件大小转换为B KB MB GB TB PB EB ZB YB
  const formatBytes = (size: number): string => {
    const step = 1024;
    let tempSize = size;
    let i = 0;
    while (tempSize > step && i < 8) {
      i += 1;
      tempSize /= step;
    }
    return `${tempSize.toFixed(2)}${BYTES_ARRAY[i]}`;
  };

  const afterUpload = () => {
    searchFile();
  };

  // func：下载一个文件
  const handleDownload = (row: FileRecord) => {
    window.open(row.url, '_blank');
  };
  // func: 删除一个文件
  const removeFile = async (row: FileRecord) => {
    try {
      await deleteFile(row.id as string);
      Message.success('操作成功');
    } finally {
      searchFile();
    }
  };
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    border-radius: var(--border-radius-default);
  }
</style>
